<?php

namespace App\Http\Logic\Api;

use Exception;

class AuditToken
{
    private static string $method = 'AES-128-ECB';

    public static function getToken($userInfo): string
    {
        $data = [
            'created_at' => time(),
            'exp_time' => time() + ((3600 * 24) * 7),
            'user_id' => $userInfo['id'],
            'phone' => $userInfo['phone'],
            'name' => $userInfo['nickname']
        ];
        $key = substr(hash('sha256', env('TOKEN_KEY'), true), 0, 16);

        return base64_encode(openssl_encrypt(json_encode($data), self::$method, $key, OPENSSL_RAW_DATA));
    }

    /**
     * @throws Exception
     */
    public static function decryptToken($toKen): array
    {
        try {
            $encrypted = base64_decode($toKen);
            $key = substr(hash('sha256', env('TOKEN_KEY'), true), 0, 16);
            $decrypted = openssl_decrypt($encrypted, self::$method, $key, OPENSSL_RAW_DATA);

            if ($decrypted === false) {
                throw new Exception(openssl_error_string());
            }

            return json_decode($decrypted, true);
        } catch (Exception $e) {
            throw new Exception('token验证失败');
        }
    }
}
